//
//  JYPicContainerView.m
//  JYEducation-Parent
//
//  Created by RD on 2017/9/20.
//  Copyright © 2017年 com.RDInfo. All rights reserved.
//

#import "JYPicContainerView.h"
#import "PBViewController.h"
#import "JYAlertView.h"

@interface JYPicContainerView ()<PBViewControllerDataSource,PBViewControllerDelegate>

@property (nonatomic, strong) NSArray *imageViewArray;
@end

@implementation JYPicContainerView

- (instancetype)init {
    if (self = [super init]) {
        NSMutableArray *tempArray = [NSMutableArray array];
        for (int i=0; i<9; i++) {
            UIImageView *imageView = [[UIImageView alloc]init];
            imageView.contentMode = UIViewContentModeScaleAspectFill;
            imageView.clipsToBounds = YES;
            [self addSubview:imageView];
            imageView.userInteractionEnabled = YES;
            imageView.tag = i;
            UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(tapImageView:)];
            [imageView addGestureRecognizer:tap];
            [tempArray addObject:imageView];
        }
        self.imageViewArray = [tempArray copy];
    }
    return self;
}

- (void)setPhotoPathArray:(NSArray *)photoPathArray {
    _photoPathArray = photoPathArray;
    for (long i=photoPathArray.count; i<self.imageViewArray.count; i++) {
        UIImageView *imageView = [self.imageViewArray objectAtIndex:i];
        imageView.hidden = YES;
    }
    if (_photoPathArray.count == 0) {
        self.height = 0;
        self.fixedHeight = @(0);
        return;
    }
	CGFloat itemW = photoPathArray.count == 1?screen_Width - 30: itemWidth;
	CGFloat itemH = photoPathArray.count == 1?(screen_Width - 30)/16*9: itemHeight;
    long perRowItemCount = 3;
    NSInteger count = photoPathArray.count > self.imageViewArray.count ? self.imageViewArray.count : photoPathArray.count;
    for (int i=0; i< count; i++) {
        
        long columnIndex = i % perRowItemCount;
        long rowIndex = i / perRowItemCount;
        UIImageView *imageView = self.imageViewArray[i];
        imageView.hidden = NO;
        NSURL *url = [NSURL URLWithString:photoPathArray[i]];
        [imageView sd_setImageWithURL:url placeholderImage:DEFAULT_SMALL_IMAGE];
        CGFloat itemX = columnIndex *(itemW +imageDivide);
        CGFloat itemY = rowIndex *(itemH +imageDivide);
        imageView.frame = CGRectMake(itemX, itemY, itemW, itemH);
    }
    
    CGFloat w = perRowItemCount *itemW +(perRowItemCount -1)*imageDivide;
    int columnCount = ceilf(photoPathArray.count*1.0/perRowItemCount);
    CGFloat h = columnCount *itemH +(columnCount - 1)*imageDivide;
    self.width = w;
    self.height = h;
    
    self.fixedHeight = @(h);
    self.fixedWidth = @(w);
}

#pragma mark - private actions

- (void)tapImageView:(UITapGestureRecognizer *)tap
{
    UIView *imageView = tap.view;
    PBViewController *_pbViewController = [PBViewController new];
    _pbViewController.blurBackground = NO;
    _pbViewController.pb_dataSource = self;
    _pbViewController.pb_delegate = self;
    _pbViewController.pb_startPage = imageView.tag;
    UIViewController *vc = [Utils getCurrentVCWithSubView:self];
    [vc presentViewController:_pbViewController animated:YES completion:nil];
}



#pragma mark --图片浏览器的数据源方法--
- (NSInteger)numberOfPagesInViewController:(PBViewController *)viewController {
    return self.photoPathArray.count;
}

- (UIImage *)viewController:(PBViewController *)viewController imageForPageAtIndex:(NSInteger)index
{
    if(index <= self.imageViewArray.count - 1) {
        
        UIImageView *imageView = self.subviews[index];
        return imageView.image;
    }else {
        
        return nil;
    }
}

-(void)viewController:(PBViewController *)viewController presentImageView:(UIImageView *)imageView forPageAtIndex:(NSInteger)index progressHandler:(void (^)(NSInteger, NSInteger, NSURL *))progressHandler
{
    
    NSString *url = self.photoPathArray[index];
    
    [imageView sd_setImageWithURL:[NSURL URLWithString:url]];
}

- (UIView *)thumbViewForPageAtIndex:(NSInteger)index {
    if(index <= self.imageViewArray.count - 1) {
        
        UIImageView *imageView = self.subviews[index];
        return imageView;
    }else {
        return nil;
    }
}

//- (void)viewController:(PBViewController *)viewController presentImageView:(UIImageView *)imageView
//        forPageAtIndex:(NSInteger)index progressHandler:(void (^)(NSInteger, NSInteger, NSURL *))progressHandler
//{
//    NSURL *url = [NSURL URLWithString:_photoPath];
//    [imageView sd_setImageWithURL:url placeholderImage:DEFAULT_SMALL_IMAGE];
//}

#pragma mark --图片浏览器的代理方法--
- (void)viewController:(PBViewController *)viewController didSingleTapedPageAtIndex:(NSInteger)index presentedImage:(UIImage *)presentedImage {
    NSLog(@"didSinglePressedPageAtInex:%zd", index);
    UIViewController *vc = [Utils getCurrentVCWithSubView:self];
    [vc dismissViewControllerAnimated:YES completion:nil];
}

- (void)viewController:(PBViewController *)viewController didLongPressedPageAtIndex:(NSInteger)index presentedImage:(UIImage *)presentedImage {
    NSLog(@"didLongPressedPageAtIndex: %@", @(index));
    WS(weakSelf);
    [JYAlertView showAlertViewWithMessage:@"是否要保存图片到相册？" titleArr:@[@"取消",@"保存"] titleColors:@[DarkBlackColor, BlueColor] actionHandler:^(NSInteger tag) {
        
        if (tag == 1) {
			NSLog(@"保存图片");
            [weakSelf loadImageFinished:presentedImage];
        }
    }];
}

#pragma mark --保存图片到相册--
- (void)loadImageFinished:(UIImage *)image
{
    UIImageWriteToSavedPhotosAlbum(image, self, @selector(image:didFinishSavingWithError:contextInfo:), (__bridge void *)self);
}

- (void)image:(UIImage *)image didFinishSavingWithError:(NSError *)error contextInfo:(void *)contextInfo
{
    DLog(@"image = %@, error = %@, contextInfo = %@", image, error, contextInfo);
    NSString *message = nil;
    if(error) {
        message = @"保存失败";
		[MBProgressHUD showSuccess:message];
    }else {
        message = @"保存成功";
		[MBProgressHUD showError:message];

    }
//    [MessageTool showMessage:message isError:NO];


	
}

@end
